import { NextRequest, NextResponse } from 'next/server';
import { getDbInstance } from '@/lib/sqlite-database';
import { verifyAuth, verifyCreatePermission, verifyDeletePermission } from '@/lib/auth-middleware';

export async function GET(request: NextRequest) {
  try {
    // 验证用户认证状态
    const authResult = await verifyAuth();
    if (!authResult.success) {
      return NextResponse.json({
        success: false,
        error: authResult.error
      }, { status: authResult.status || 401 });
    }
    const db = getDbInstance();
    const searchParams = request.nextUrl.searchParams;
    const specialty = searchParams.get('specialty');
    const deviceId = searchParams.get('deviceId');
    const withParameters = searchParams.get('withParameters') === 'true';
    const getMaxId = searchParams.get('getMaxId');

    if (getMaxId === 'true') {
      const result = db.get('SELECT MAX(id) as maxId FROM devices');
      return NextResponse.json({ maxId: result?.maxId || 0 });
    }

    if (deviceId) {
      const device = db.getDeviceByDeviceId(deviceId);
      if (!device) {
        return NextResponse.json({ error: '设备未找到' }, { status: 404 });
      }
      if (withParameters && device.id) {
        const deviceWithParams = db.getDeviceWithParameters(device.id);
        return NextResponse.json(deviceWithParams);
      }
      return NextResponse.json(device);
    }

    let devices;
    if (specialty) {
      devices = db.getDevicesBySpecialty(specialty);
    } else {
      devices = db.getAllDevices();
    }

    if (withParameters) {
      const devicesWithParams = devices.map(device => {
        if (device.id) {
          return db.getDeviceWithParameters(device.id);
        }
        return { device, namingParameters: [], positionParameters: [], baseParameters: [] };
      });
      return NextResponse.json(devicesWithParams);
    }

    return NextResponse.json(devices);

  } catch (error) {
    console.error('获取SQLite设备数据错误:', error);
    return NextResponse.json({
      error: `获取设备数据失败: ${error instanceof Error ? error.message : '未知错误'}`
    }, { status: 500 });
  }
}

export async function POST(request: NextRequest) {
  try {
    const db = getDbInstance();
    const deviceData = await request.json();
    
    // 为复制的设备生成一个新的唯一ID
    // 删除旧的id和device_id，以避免违反数据库约束
    delete deviceData.id;
    
    // 生成基于原设备ID的递增序号
    let newDeviceId;
    if (deviceData.original_device_id) {
      // 获取所有以原设备ID为前缀的设备
      const baseDeviceId = deviceData.original_device_id;
      const existingDevices = db.getAllDevices();
      
      // 查找所有以baseDeviceId开头的设备ID
      const similarDeviceIds = existingDevices
        .map(device => device.device_id)
        .filter(id => id && (id === baseDeviceId || id.startsWith(baseDeviceId + '-')));
      
      // 找到最大的序号
      let maxSuffix = 0;
      for (const deviceId of similarDeviceIds) {
        if (deviceId === baseDeviceId) {
          // 原设备，序号为0
          continue;
        } else if (deviceId.startsWith(baseDeviceId + '-')) {
          // 提取序号部分
          const suffixPart = deviceId.substring(baseDeviceId.length + 1);
          const suffixNumber = parseInt(suffixPart, 10);
          if (!isNaN(suffixNumber) && suffixNumber > maxSuffix) {
            maxSuffix = suffixNumber;
          }
        }
      }
      
      // 生成新的序号
      const nextSuffix = maxSuffix + 1;
      newDeviceId = `${baseDeviceId}-${nextSuffix}`;
    } else {
      // 如果没有原设备ID，使用旧的生成方式
      newDeviceId = `DUP-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
    }
    
    deviceData.device_id = newDeviceId;

    const newDevice = db.insertDevice(deviceData);
    
    // 如果新设备创建成功，并且有关联的参数，也一并复制
    if (newDevice && newDevice.id && deviceData.namingParameters) {
        for (const param of deviceData.namingParameters) {
            delete param.id; // 删除旧的参数ID
            db.insertNamingParameter({ ...param, device_id: newDevice.id });
        }
    }
    if (newDevice && newDevice.id && deviceData.positionParameters) {
        for (const param of deviceData.positionParameters) {
            delete param.id; // 删除旧的参数ID
            db.insertPositionParameter({ ...param, device_id: newDevice.id });
        }
    }
     if (newDevice && newDevice.id && deviceData.baseParameters) {
        for (const param of deviceData.baseParameters) {
            delete param.id; // 删除旧的参数ID
            db.insertBaseParameter({ ...param, device_id: newDevice.id });
        }
    }

    // 返回新创建的设备，不包含参数以简化响应
    const finalDevice = db.getDeviceByDeviceId(deviceData.device_id);

    return NextResponse.json({
      success: true,
      device: finalDevice,
      message: '设备复制成功'
    });
  } catch (error) {
    console.error('创建设备错误:', error);
    return NextResponse.json({
      success: false,
      error: `创建设备失败: ${error instanceof Error ? error.message : '未知错误'}`
    }, { status: 500 });
  }
}

export async function PUT(request: NextRequest) {
  try {
    // 验证用户编辑权限
    const authResult = await verifyCreatePermission();
    if (!authResult.success) {
      return NextResponse.json({
        success: false,
        error: authResult.error
      }, { status: authResult.status || 401 });
    }

    if (!authResult.canCreate) {
      return NextResponse.json({
        success: false,
        error: '权限不足：无法编辑设备信息'
      }, { status: 403 });
    }
    const db = getDbInstance();
    const data = await request.json();
    const { deviceId, ...updates } = data;
    const result = db.updateDevice(
      Number(deviceId),
      updates
    );
    if (!result) {
      return NextResponse.json({ error: '设备更新失败' }, { status: 404 });
    }
    return NextResponse.json({ success: true, device: result });
  } catch (error) {
    console.error('更新设备时出错:', error);
    return NextResponse.json(
      { error: '更新设备失败: ' + (error as Error).message },
      { status: 500 }
    );
  }
}

export async function PATCH(request: NextRequest) {
  try {
    // 验证用户编辑权限
    const authResult = await verifyCreatePermission();
    if (!authResult.success) {
      return NextResponse.json({
        success: false,
        error: authResult.error
      }, { status: authResult.status || 401 });
    }

    if (!authResult.canCreate) {
      return NextResponse.json({
        success: false,
        error: '权限不足：无法修改设备信息'
      }, { status: 403 });
    }
    const db = getDbInstance();
    const data = await request.json();
    const { action, updates } = data;
    if (action === 'batchUpdateRemarks') {
      const results = updates.map((update: { deviceId: string; remarks: string }) => {
        return db.updateDevice(
          Number(update.deviceId),
          { remarks: update.remarks }
        );
      });
      return NextResponse.json({ success: true, results });
    }
    return NextResponse.json({ error: '不支持的操作' }, { status: 400 });
  } catch (error) {
    console.error('批量更新备注时出错:', error);
    return NextResponse.json(
      { error: '批量更新备注失败: ' + (error as Error).message },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    // Verify authentication and delete permissions
    const authResult = await verifyDeletePermission();
    if (!authResult.success) {
      return NextResponse.json({
        success: false,
        error: authResult.error
      }, { status: authResult.status || 401 });
    }

    if (!authResult.canDelete) {
      return NextResponse.json({
        success: false,
        error: '权限不足：无法删除设备'
      }, { status: 403 });
    }

    const db = getDbInstance();
    const searchParams = request.nextUrl.searchParams;
    const deviceId = searchParams.get('deviceId');
    
    if (!deviceId) {
      return NextResponse.json({ error: '缺少设备ID' }, { status: 400 });
    }
    
    const success = db.deleteDevice(deviceId);
    
    if (success) {
      return NextResponse.json({
        success: true,
        message: '设备删除成功'
      });
    } else {
      return NextResponse.json({ error: '设备删除失败，设备可能不存在' }, { status: 404 });
    }
  } catch (error) {
    console.error('删除设备时出错:', error);
    return NextResponse.json(
      { error: '删除设备失败: ' + (error as Error).message },
      { status: 500 }
    );
  }
}